<template>
  <div>
    <div v-if="fileList[0]" style="width: 100px; height: 100px; margin-top: 10px">
      <div class="reupload" @click="reuploadHandle">
        <Upload
          :accept="getStringAccept"
          :multiple="false"
          :show-upload-list="false"
          class="upload"
          :before-upload="beforeUpload"
          style="width: 100%; margin-left: 0"
          action=""
          @change="uploadChange"
        >
          <img
            v-if="fileList[0].fileUrl"
            :src="fileList[0].fileUrl"
            style="width: 100px; height: 100px"
            alt=""
          />
          <div v-else class="avatar-uploader">
            <PlusOutlined />
            <div class="ant-upload-text">Upload</div>
          </div>
        </Upload>
      </div>
    </div>
    <div v-else style="width: 100px; height: 100px; margin-top: 10px">
      <div class="reupload">
        <Upload
          :accept="getStringAccept"
          :multiple="false"
          :show-upload-list="false"
          class="upload"
          :before-upload="beforeUpload"
          style="width: 100%"
          @change="uploadChange"
        >
          <img
            style="width: 100px; height: 100px"
            v-if="$props['value'] && typeof $props['value'] == 'string'"
            :src="$props['value'].substring(0, $props['value'].indexOf('?'))"
            alt="avatar"
          />
          <div v-else class="avatar-uploader">
            <PlusOutlined />
            <div class="ant-upload-text">上传</div>
          </div>
          <!-- <span
            style="
              line-height: 98px;
              text-align: center;
              width: 100px;
              display: inline-block;
              border: 1px solid #666;
            "
            >重新上传</span
          > -->
        </Upload>
      </div>
      <!-- <img
        v-if="$props['value'] && typeof $props['value'] == 'string'"
        :src="$props['value'].substring(0, $props['value'].indexOf('?'))"
        style="width: 100%; height: 100%"
        alt=""
      /> -->
    </div>
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, watch, toRefs, unref, computed } from 'vue';
  import { LoadingOutlined, PlusOutlined } from '@ant-design/icons-vue';
  import { useUploadType } from './useUpload';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { isFunction } from '/@/utils/is';
  import { FileItem, UploadResultStatus } from './typing';
  import { warn } from '/@/utils/log';
  import { uploadContainerProps } from './props';
  import { omit } from 'lodash-es';
  import { checkImgType, getBase64WithFile, getMd5WithFile } from './helper';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { buildUUID } from '/@/utils/uuid';
  import { FileUpload } from '/@/api/sys/upload';
  import { Upload } from 'ant-design-vue';
  const headPortrait = ref('');
  export default defineComponent({
    name: 'CoverUpload',
    components: { Upload, LoadingOutlined, PlusOutlined },
    props: uploadContainerProps,
    emits: ['change', 'delete', 'update:value'],

    setup(props, { emit, attrs }) {
      const { t } = useI18n();
      const { uploadType, accept, helpText, maxNumber, maxSize } = toRefs(props);
      const dataMap = ref<Object>({});
      const fileList = ref<FileUpload[]>([]);
      const fileListDel = ref<FileUpload[]>([]);
      const avatar = ref([]);
      const { getStringAccept } = useUploadType({
        uploadTypeRef: uploadType,
        acceptRef: accept,
        helpTextRef: helpText,
        maxNumberRef: maxNumber,
        maxSizeRef: maxSize,
      });
      const { createMessage } = useMessage();
      const showPreview = computed(() => {
        const { emptyHidePreview } = props;
        if (!emptyHidePreview) return true;
        return emptyHidePreview ? fileList.value.length > 0 : true;
      });

      const bindValue = computed(() => {
        const value = { ...attrs, ...props };
        return omit(value, 'onChange');
      });

      watch(
        () => props.value,
        (value = '') => {
          if (typeof value == 'string') {
            headPortrait.value = value;
          }
        },
        { immediate: true },
      );

      watch(
        () => [props.bizKey, props.loadTime],
        () => {
          // loadFileList();
        },
        { immediate: true },
      );

      // 上传前校验
      function beforeUpload(file: File) {
        const { size, name } = file;
        const { maxSize, bizKey, bizType, uploadType } = props;
        // 设置最大值，则判断
        if (maxSize && file.size / 1024 / 1024 >= maxSize) {
          createMessage.error(t('component.upload.maxSizeMultiple', [maxSize]));
          return false;
        }
        getMd5WithFile(file, 10 * 1024 * 1024).then(({ result: fileMd5 }) => {
          const commonItem = {
            id: buildUUID(),
            file,
            size,
            name,
            percent: 0,
            type: name.split('.').pop(),
            fileMd5: fileMd5,
            fileName: name,
            fileUploadId: '',
            fileEntityId: '',
            bizKey,
            bizType,
            uploadType,
          };
          // 生成图片缩略图
          if (checkImgType(file)) {
            getBase64WithFile(file).then(({ result: fileUrl }) => {
              addFileItem({
                fileUrl,
                ...commonItem,
              });
            });
          } else {
            addFileItem(commonItem);
          }
        });
        return false;
      }

      function addFileItem(record: FileItem) {
        if (!props.isLazy) {
          uploadApiByItem(record);
        }
      }

      async function uploadApiByItem(item: FileItem) {
        const { checkmd5, api } = props;
        if (!api || !isFunction(api)) {
          return warn('upload api must exist and be a function');
        }
        try {
          item.status = UploadResultStatus.UPLOADING;
          if (checkmd5) {
            const data = await props.api?.({
              bizKey: item.bizKey,
              bizType: item.bizType,
              fileMd5: item.fileMd5,
              fileName: item.fileName,
            });
            if (data.result == 'true') {
              item.percent = 100;
              item.responseData = data;
              fileList.value = [data.fileUpload];
              emit('change', data.fileUpload);
            } else {
              item.fileUploadId = data.fileUploadId;
              item.fileEntityId = data.fileEntityId;
            }
          }
          if (item.percent != 100) {
            const { data } = await props.api?.(
              {
                bizKey: item.bizKey,
                bizType: item.bizType,
                uploadType: item.uploadType,
                fileMd5: item.fileMd5,
                fileName: item.fileName,
                fileUploadId: item.fileUploadId,
                fileEntityId: item.fileEntityId,
                ...(props.uploadParams || {}),
                file: item.file,
              },
              function onUploadProgress(progressEvent: ProgressEvent) {
                const complete = ((progressEvent.loaded / progressEvent.total) * 100) | 0;
                item.percent = complete;
              },
            );
            item.responseData = data;
          }
          item.status = UploadResultStatus.SUCCESS;
          return {
            success: true,
            error: null,
          };
        } catch (e) {
          console.log(e);
          item.status = UploadResultStatus.ERROR;
          return {
            success: false,
            error: e,
          };
        }
      }

      const reuploadHandle = () => {
        // if (JSON.stringify(fileList.value) != '[]') {
        //   const removed = fileList.value.splice(0, 1);
        //   handleDelete(removed.values);
        // }
      };
      // // 上传modal保存操作
      // function handleChange(records: FileUpload[]) {
      //   fileList.value = [...unref(fileList), ...(records || [])];
      //   dataMap.value[props.bizType] = fileList.value.map((item) => item.id).join(',');
      //   emit('update:value', dataMap.value);
      //   avatar.value = records[0];
      //   emit('change', records[0]);
      // }

      function uploadChange(info) {
        console.log(123);
      }
      function handleDelete(record: FileUpload) {
        fileListDel.value.push(record);
        dataMap.value[props.bizType + '__del'] = fileListDel.value.map((item) => item.id).join(',');
        emit('delete', record);
        emit('update:value', dataMap.value);
        emit('change', dataMap.value);
      }

      return {
        // handleChange,
        uploadChange,
        beforeUpload,
        uploadApiByItem,
        getStringAccept,
        fileList,
        showPreview,
        bindValue,
        avatar,
        handleDelete,
        reuploadHandle,
        t,
      };
    },
  });
</script>
<style>
  .reupload {
    width: 100px;
    height: 100px;
    position: absolute;
    border: 1px dashed #d9d9d9;
    border-radius: 8px;
    overflow: hidden;
    /* background-color: rgba(0, 0, 0, 0); */
    /* color: rgba(0, 0, 0, 0); */
    /* animation-iteration-count: infinite; */
  }
  .reupload:hover {
    cursor: pointer;
    /* animation-duration: 0.5s; */
    /* animation-name: aniReupload; */
    /* animation-fill-mode: forwards; */
  }
  /* .reupload:hover .upload span {
    color: rgba(255, 255, 255, 1);
    border: 0 !important;
  } */
  .upload {
    position: absolute;
  }
  /* .reupload span {
    position: relative;
    z-index: 10;
    color: rgba(255, 255, 255, 0);
    cursor: pointer;
  } */
  .avatar-uploader {
    width: 100px;
    height: 100px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    text-align: center;
  }
  @keyframes aniReupload {
    from {
      background-color: rgba(0, 0, 0, 0);
      color: rgba(255, 255, 255, 0);
    }
    to {
      background-color: rgba(0, 0, 0, 0.5);
      color: rgba(255, 255, 255, 1);
    }
  }
</style>
